package com.tiniplanet.webgate.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.tiniplanet.webgate.service.EmployeeService;

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler{
	
	@Autowired
	EmployeeService employeeService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication auth) throws IOException,
			ServletException {		
		User user = (User) auth.getPrincipal();
		request.getSession().setAttribute("employee", employeeService.getById(user.getUsername()));
		
		//now restore the default work flow (SavedRequestAwareAuthenticationSuccessHandler is the default AuthenticationSuccessHandler that Spring uses,
        // see: http://static.springsource.org/spring-security/site/docs/3.0.x/reference/core-web-filters.html#form-login-flow-handling )
		(new SavedRequestAwareAuthenticationSuccessHandler()).onAuthenticationSuccess(request, response, auth);
	}

}
